﻿using System;
using System.Net;
using System.Windows;
using System.Device.Location;

namespace $safeprojectname$
{
    public class GeoLocationHelper
    {
        private GeoCoordinateWatcher watcher;
        private GeoCoordinate _location;
        private GeoPositionStatus _status;

        public GeoCoordinate Location
        {
            get { return _location; }
        }

        public GeoPositionStatus Status
        {
            get { return _status; }
        }

        public delegate void GeoPositionLocationChangedEventHandler(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e);
        public delegate void GeoPositionStatusChangedEventHandler(object sender, GeoPositionStatusChangedEventArgs e);

        public event GeoPositionLocationChangedEventHandler LocationChanged;
        public event GeoPositionStatusChangedEventHandler StatusChanged;

        /// <summary>
        /// Initializes the Watcher. Call the constructor again to get the next location.
        /// </summary>
        /// <param name="accuracy">Accuracy of location</param>
        /// <param name="movementThreshold">Distance in Meters</param>
        public GeoLocationHelper(GeoPositionAccuracy accuracy, double movementThreshold)
        {
            // Reinitialize the GeoCoordinateWatcher
            watcher = new GeoCoordinateWatcher(accuracy);
            watcher.MovementThreshold = movementThreshold;

            // Add event handlers for StatusChanged and PositionChanged events
            watcher.StatusChanged += new EventHandler<GeoPositionStatusChangedEventArgs>(watcher_StatusChanged);
            watcher.PositionChanged += new EventHandler<GeoPositionChangedEventArgs<GeoCoordinate>>(watcher_PositionChanged);

            watcher.Start();
        }

        void watcher_StatusChanged(object sender, GeoPositionStatusChangedEventArgs e)
        {
            Deployment.Current.Dispatcher.BeginInvoke(() => MyStatusChanged(e));
        }

        void watcher_PositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e)
        {
            Deployment.Current.Dispatcher.BeginInvoke(() => MyPositionChanged(e));
        }

        /// <summary>
        /// Custom method called from the StatusChanged event handler
        /// </summary>
        /// <param name="e"></param>
        void MyStatusChanged(GeoPositionStatusChangedEventArgs e)
        {
            if (StatusChanged != null)
            {
                StatusChanged(this, e);
            }
        }
        void MyPositionChanged(GeoPositionChangedEventArgs<GeoCoordinate> e)
        { 
            if (LocationChanged != null)
            {
                LocationChanged(this, e);
            }
        }
    }
}
